package com.weiweiqin.controller.back;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.weiweiqin.constants.Constants;
import com.weiweiqin.model.Order;
import com.weiweiqin.service.OrderService;
import com.weiweiqin.utils.Dom4jUtil;
import com.weiweiqin.utils.ExcelUtil;
import com.weiweiqin.utils.MobileFromUtil;
import com.weiweiqin.utils.RandomValidateCode;
import com.weiweiqin.vo.common.CartVO;
import com.weiweiqin.vo.common.OrderQueryVO;
import com.weiweiqin.vo.common.OrderTabVO;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.Result;
import com.weiweiqin.vo.common.ShipVO;

@Controller
@RequestMapping("admin/order")
public class OrderController {

	private static final Logger logger = LoggerFactory
			.getLogger(OrderController.class);
	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/edit.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String edit(Order order) {
		logger.info("Enter method edit....，order=" + order);
		Result result = new Result();
		// 获取下单时间
		Order orderDa = orderService.get(order.getId());
		order.setUpdateDate(orderDa.getUpdateDate());
		orderService.update(order);
		logger.info("End method edit....");
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/editForBack.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String editForBack(Order order, HttpServletRequest request,
			HttpSession session) {
		logger.info("Enter method add....，order=" + order);
		logger.info("ip=" + request.getRemoteAddr());
		Result result = new Result();
		// 保存订单信息
		try {
			Order order2 = orderService.get(order.getId());
			order2.setTotalPrice(order.getTotalPrice());
			order2.setName(order.getName());
			order2.setMobile(order.getMobile());
			order2.setAddr(order.getAddr());
			order2.setRemark(order.getRemark());
			orderService.update(order2);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}

		result.setResult(true);
		result.setObj(order);
		return result.toJson();
	}

	@RequestMapping(value = "/memo.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String memo(int id, String memo, int status,HttpServletRequest req) {
		logger.info("Enter method memo....，id=" + id + "memo=" + memo);
		Result result = new Result();
		HttpSession session = req.getSession();
		String ip = req.getRemoteAddr();
		logger.info("oper ip=" + ip);
		if (session == null || session.getAttribute("user") == null) {
			result.setResult(false);
			result.setErrorMsg("您访问的地址不存在！");
			return result.toJson();
		}
		
		Order order = orderService.get(id);
		if (null != order) {
			order.setMemo(memo);
			order.setStatus(status);
			orderService.update(order);
		} else {
			result.setResult(false);
			logger.info("不存在该订单");
			result.setErrorMsg("不存在该订单");
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/del.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String del(int id,HttpServletRequest req) {
		logger.info("Enter method del....,id=" + id);
		Result result = new Result();
		HttpSession session = req.getSession();
		if (session == null || session.getAttribute("user") == null) {
			result.setResult(false);
			result.setErrorMsg("您访问的地址不存在！");
			return result.toJson();
		}
		Order order = orderService.get(id);
		order.setMark(-1);
		orderService.update(order);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/get.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String get(int id,HttpServletRequest req) {
		logger.info("Enter method get....");
		Result result = new Result();
		HttpSession session = req.getSession();
		if (session == null || session.getAttribute("user") == null) {
			result.setResult(false);
			result.setErrorMsg("您访问的地址不存在！");
			return result.toJson();
		}
		Order order = orderService.get(id);
		result.setObj(order);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/list.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String pageList(OrderQueryVO orderVO,String showMobileFrom,HttpServletRequest req) {
		logger.info("Enter pageList ...,orderVO=" + orderVO);
		Result result = new Result();
		
		HttpSession session = req.getSession();
		if (session == null || session.getAttribute("user") == null) {
			result.setResult(false);
			result.setErrorMsg("您访问的地址不存在！");
			return result.toJson();
		}
		
		String ip = req.getRemoteAddr();
		logger.info("登录订单ip=" + ip);
		
		Page page = new Page();
		page.setCurrPage(orderVO.getCurrPage());
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("status", orderVO.getStatus());
		if (!StringUtils.isEmpty(orderVO.getTitle())) {
			conditions.put("title", orderVO.getTitle().trim());
		}
		
		if (!StringUtils.isEmpty(orderVO.getHost())) {
			conditions.put("host", orderVO.getHost().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getOuterid())) {
			conditions.put("outerid", orderVO.getOuterid().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getName())) {
			conditions.put("name", orderVO.getName().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getMemo())) {
			conditions.put("memo", orderVO.getMemo().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getMobile())) {
			conditions.put("mobile", orderVO.getMobile().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getAddr())) {
			conditions.put("addr", orderVO.getAddr().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getStartDate())
				&& !StringUtils.isEmpty(orderVO.getEndDate())) {
			conditions.put("startDate", orderVO.getStartDate());
			conditions.put("endDate", orderVO.getEndDate());
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<Order> orderList = orderService.pageList(page, conditions);
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();

		if (null != orderList) {
			for (Order order : orderList) {
				//如果是待处理订单,显示手机归属地
				if(orderVO.getStatus() == 0 &&  null !=showMobileFrom && !"noshow".equals(showMobileFrom)){
					String mobile = order.getMobile();
					try {
						String mobileAddr = MobileFromUtil.getMobileFrom(mobile);
						mobile = mobile + "("+mobileAddr+")";
						order.setMobile(mobile);
					} catch (Exception e) {
						mobile = mobile + "(获取失败)";
						order.setMobile(mobile);
						logger.error("获取手机号码归属地异常。。。",e);
					}
				}
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				List<CartVO> cartVOList = orderService.getCartVOList(order
						.getId());
				vo.setGoodsList(cartVOList);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		int totalCount = orderService.totalCount(conditions);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("totalCount", totalCount);
		mp.put("list", orderVOList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}
	
	@RequestMapping(value = "/readySendList.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String readySendList(HttpServletRequest req) {
		logger.info("Enter readySendList ...");
		Result result = new Result();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		//去除通过名称查询
		//List<Order> orderList = orderService.getByGoodsTitle(title);
		List<Order> orderList = orderService.getProcessed1();
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();
		if (null != orderList) {
			for (Order order : orderList) {
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				List<CartVO> cartVOList = orderService.getCartVOList(order
						.getId());
				vo.setGoodsList(cartVOList);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		result.setObj(orderVOList);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/export.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	public void export(OrderQueryVO orderVO, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Enter method export...,orderVO=" + orderVO);
		Map<String, Object> conditions = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(orderVO.getTitle())) {
			conditions.put("title", orderVO.getTitle());
		}
		if (!StringUtils.isEmpty(orderVO.getName())) {
			conditions.put("name", orderVO.getName());
		}
		if (!StringUtils.isEmpty(orderVO.getMobile())) {
			conditions.put("mobile", orderVO.getMobile());
		}
		if (!StringUtils.isEmpty(orderVO.getAddr())) {
			conditions.put("addr", orderVO.getAddr());
		}

		if (!StringUtils.isEmpty(orderVO.getMemo())) {
			conditions.put("memo", orderVO.getMemo());
		}

		if (!StringUtils.isEmpty(orderVO.getStartDate())
				&& !StringUtils.isEmpty(orderVO.getEndDate())) {
			conditions.put("startDate", orderVO.getStartDate());
			conditions.put("endDate", orderVO.getEndDate());
		}

		if (orderVO.getStatus() != -1) {
			conditions.put("status", orderVO.getStatus());
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<Order> orderList = orderService.export(conditions);
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();
		if (null != orderList) {
			for (Order order : orderList) {
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				List<CartVO> cartVOList = orderService.getCartVOList(order
						.getId());
				vo.setGoodsList(cartVOList);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		ExcelUtil.exportByList(orderVOList, request, response);
	}
	
	@RequestMapping(value = "/exportSF.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	public void exportSF(OrderQueryVO orderVO, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Enter method exportSF...,orderVO=" + orderVO);
		Map<String, Object> conditions = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(orderVO.getTitle())) {
			conditions.put("title", orderVO.getTitle());
		}
		if (!StringUtils.isEmpty(orderVO.getName())) {
			conditions.put("name", orderVO.getName());
		}
		if (!StringUtils.isEmpty(orderVO.getMobile())) {
			conditions.put("mobile", orderVO.getMobile());
		}
		if (!StringUtils.isEmpty(orderVO.getAddr())) {
			conditions.put("addr", orderVO.getAddr());
		}

		if (!StringUtils.isEmpty(orderVO.getMemo())) {
			conditions.put("memo", orderVO.getMemo());
		}

		if (!StringUtils.isEmpty(orderVO.getStartDate())
				&& !StringUtils.isEmpty(orderVO.getEndDate())) {
			conditions.put("startDate", orderVO.getStartDate());
			conditions.put("endDate", orderVO.getEndDate());
		}

		if (orderVO.getStatus() != -1) {
			conditions.put("status", orderVO.getStatus());
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<Order> orderList = orderService.export(conditions);
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();
		if (null != orderList) {
			for (Order order : orderList) {
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				List<CartVO> cartVOList = orderService.getCartVOList(order
						.getId());
				vo.setGoodsList(cartVOList);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		ExcelUtil.exportSF(orderVOList, request, response);
	}

	@RequestMapping(value = "/genCode.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	public void genValidateCode(HttpServletRequest request,
			HttpServletResponse response) {

		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		RandomValidateCode randomValidateCode = new RandomValidateCode();
		try {
			// 输出图片方法
			randomValidateCode.getRandcode(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 后台发货操作
	 * 
	 * @param outerid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/ship.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String ship(ShipVO shipVO, int id, HttpServletRequest request) {

		Result result = new Result();
		try {
			Order order = orderService.get(id);
			if (null != order) {
				order.setExpressName(shipVO.getExpressName());
				order.setExpressNo(shipVO.getExpressNo());
				order.setExpressType(shipVO.getExpressType());
				order.setMemo(shipVO.getMemo());
				if (Constants.Order.PAY_ZHIFUBAO == order.getPayType()) {
					// 把请求参数打包成数组
					Map<String, String> sParaTemp = new HashMap<String, String>();
					sParaTemp.put("service", "send_goods_confirm_by_platform");
					sParaTemp.put("partner", AlipayConfig.partner);
					sParaTemp.put("_input_charset", AlipayConfig.input_charset);
					sParaTemp.put("trade_no", order.getTradeNo());
					sParaTemp.put("logistics_name", order.getExpressName());
					sParaTemp.put("invoice_no", order.getExpressNo());
					sParaTemp.put("transport_type",
							String.valueOf(order.getExpressType()));
					// 建立请求
					String sHtmlText = AlipaySubmit.buildRequest("", "",
							sParaTemp);
					logger.info(sHtmlText);
					Map<String, String> resultMap = Dom4jUtil
							.confirmShipResult(sHtmlText);
					// 返回成功结果，更新订单状态和信息
					if ("T".equals(resultMap.get("result"))) {
						// 订单状态变成已发货
						order.setTradeStatus("WAIT_BUYER_CONFIRM_GOODS");
						// 2：已发货
						order.setStatus(2);
						// 发货成功后更新订单
						orderService.update(order);
					} else {
						result.setResult(false);
						result.setErrorMsg(resultMap.get("errorCode"));
						return result.toJson();
					}
				} else {
					// 2：已发货
					order.setStatus(2);
					// 发货成功后更新订单
					orderService.update(order);
				}

			}
		} catch (Exception e) {
			logger.error("确认发货数据库异常......", e);
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}
	
	@RequestMapping(value = "/batchShip.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String batchShip(String wuLiuIds, HttpServletRequest request) {

		Result result = new Result();
		try {
			if(!StringUtils.isEmpty(wuLiuIds)){
				String[] wuLiuId = wuLiuIds.split(",");
				if(wuLiuId.length >0){
					for (String wuliu : wuLiuId) {
						String[] ids = wuliu.split("-");
						int orderId = Integer.parseInt(ids[0]);
						String huoId = ids[1];
						Order order = orderService.get(orderId);
						order.setExpressType(0);
						order.setExpressName("顺丰");
						order.setExpressNo(huoId);
						// 2：已发货
						order.setStatus(2);
						// 发货成功后更新订单
						orderService.update(order);
					}
				}
			}

		} catch (Exception e) {
			logger.error("批量发货数据库异常......", e);
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}
	
	@RequestMapping(value = "/orderHtml/{status}", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String orderHtml(@PathVariable int status,HttpServletRequest request) {
		Page page = new Page();
		page.setCurrPage(1);
		page.setPageSize(10000);
		Map<String, Object> conditions = new HashMap<String, Object>();
		if(status != -1){
			conditions.put("status", status);
		}
		List<Order> orderList = orderService.pageList(page, conditions);
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		if (null != orderList) {
			for (Order order : orderList) {
				//如果是待处理订单,显示手机归属地
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				List<CartVO> cartVOList = orderService.getCartVOList(order
						.getId());
				vo.setGoodsList(cartVOList);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		request.setAttribute("list", orderVOList);
		return "orderHtml";
	}
}